package com.jvm.jdbc.demo2;

import com.jvm.jdbc.util.ConnectUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * <p>
 *
 * </p>
 *
 * @author qingshan
 * @since 2020-10-11 15:27
 */
public abstract class JdbcTemplate {

    //template method
    public final Object execute(String sql) throws SQLException {

        Connection con = ConnectUtil.getConnection();
        Statement stmt = null;
        try {

            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            //
            Object result = doInStatement(rs);//abstract method
            return result;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(!con.isClosed()){
                    try {
                        con.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 子类负责实现
     * @param rs
     * @return
     */
    protected abstract Object doInStatement(ResultSet rs);
}
